package cn.wlh.learn.webmagic.pipeline;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.log.level.Level;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.Map;

/**
 * Write results in logger.<br>
 * 请不要用 ConsolePipeline , 用LoggerPipeline代替。
 * @author code4crafter@gmail.com <br>
 * @since 0.1.0
 */
public class LoggerPipeline implements Pipeline {
    private final Log logger;
    private final Level level;

    /**
     * 设置用什么级别打印日志。
     * @param logger
     * @param level
     */
    public LoggerPipeline(Log logger, Level level) {
        this.logger = logger;
        this.level = level;
    }

    /**
     * 用debug输出。
     * @param logger
     */
    public LoggerPipeline(Log logger) {
        this(logger,Level.DEBUG);
    }




    @Override
    public void process(ResultItems resultItems, Task task) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : resultItems.getAll().entrySet()) {
            sb.append(entry.getKey() );
            sb.append(":\t");
            sb.append( entry.getValue());
            sb.append( '\n');
        }
        this.logger.log(this.level,"get page: [{}] \n get ResultItems : [\n{}]",resultItems.getRequest().getUrl(),sb.toString());
    }

    public Log getLogger() {
        return logger;
    }

    public Level getLevel() {
        return level;
    }
}
